package com.longrise.android.byjk.plugins.dealsituation.cachecourse.downloadeddetail;

import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.DownloadedDetailBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;
import com.longrise.filedownloader.DownloadFileInfo;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.OnFileDownloadStatusListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by callxkj on 2017/4/6.
 * 下载详情的adapter
 */

public class DownloadedDetailRcvAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {
    public static final String TAG = "DownloadedDetailRcvAdapter";
    public final static int TYPE_0 = 0; //父类样式
    public final static int TYPE_1 = 1; //子类样式
    private final DownloadedDetailContract.Presenter mPresenter;
    List<DownloadedDetailBean> mDownloadingList = new ArrayList<>();
    List<DownloadedDetailBean> mDownloadedList = new ArrayList<>();
    List<MultiItemEntity> mDataList = new ArrayList<>();
    private DownloadManager mDownloadManager;
    private int mMode; //当前是删除模式还是正常模式
    private int mAllDownloadStatus; //全部下载或者全部暂停

    public DownloadedDetailRcvAdapter(List<MultiItemEntity> data,DownloadManager downloadManager,
                                      DownloadedDetailContract.Presenter presenter,int allDownloadStatus) {
        super(data);
        this.mDownloadManager = downloadManager;
        this.mPresenter = presenter;
        this.mAllDownloadStatus = allDownloadStatus;
        addItemType(TYPE_0, R.layout.item_downloadeddetailtitle);
        addItemType(TYPE_1, R.layout.item_downloadeddetail_child);
    }

    public void setData(DownloadedTransferBean bean,int mode) {
        this.mMode = mode;
        mDownloadingList.clear();
        mDownloadedList.clear();
        mDataList.clear();
        mDownloadingList.addAll(bean.getDownloadingList());
        mDownloadedList.addAll(bean.getDownloadedList());
        mDataList.addAll(bean.getRcvDataList());
        setNewData(mDataList);
    }

    public void setAllDownloadStatus(int status){
        mAllDownloadStatus = status;
        notifyDataSetChanged();
    }

    @Override
    protected void convert(BaseViewHolder holder, MultiItemEntity item) {
        switch (holder.getItemViewType()) {
            case TYPE_0:  //一级菜单 标题
                parseType0(holder, item);
                break;
            case TYPE_1:  //二级菜单
                parseType1(holder, item);
                break;
        }
    }

    /**
     * 解析一级菜单
     */
    private void parseType0(final BaseViewHolder holder, MultiItemEntity item) {
        final int adapterPosition = holder.getAdapterPosition();
        PrintLog.d(TAG, "parseType0:" + holder.getAdapterPosition());
        final DownloadedDetailTitleItem itemtitle = (DownloadedDetailTitleItem) item;

        holder.setText(R.id.item_downloadeddetailtitle_tv, itemtitle.getTitle())
                .setImageResource(R.id.item_downloadeddetailtitle_iconstatus,
                        itemtitle.isExpanded() ? R.drawable.icon_up : R.drawable.icon_down);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemtitle.isExpanded()) {
                    collapse(adapterPosition);
                } else {
                    expand(adapterPosition);
                }
            }
        });

    }


    /**
     * 解析二级菜单
     */
    private void parseType1(BaseViewHolder holder, MultiItemEntity item) {
        View convertView = holder.getConvertView();
        DownloadedDetailChildItem itemchild = (DownloadedDetailChildItem) item;
        final int position = itemchild.getPosition();
        if (itemchild.isDownloading()) { //正在下载里面的item
            if (position == 0) { //全部开始item
                holder.setVisible(R.id.item_downloadeddetailing_rl, false);
                holder.setVisible(R.id.item_downloadeddetailqbks_rl, true);
                if(mAllDownloadStatus==DownloadedDetailActivity.STOP){
                    holder.setImageResource(R.id.lfview_downloadeddetail_ivplay,R.drawable.start);
                    holder.setText(R.id.lfview_downloadeddetail_tvplay,"全部开始");
                }else if(mAllDownloadStatus==DownloadedDetailActivity.START){
                    holder.setImageResource(R.id.lfview_downloadeddetail_ivplay,R.drawable.stop);
                    holder.setText(R.id.lfview_downloadeddetail_tvplay,"全部暂停");
                }
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.stopOrStart(mAllDownloadStatus,mDownloadingList);
                    }
                });
            } else {
                holder.setVisible(R.id.item_downloadeddetailing_rl, true);
                holder.setVisible(R.id.item_downloadeddetailqbks_rl, false);
                final DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(position - 1);
                parseDownloading(holder, downloadedDetailBean);
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.isAbleStudy(downloadedDetailBean,position,DownloadedDetailActivity.DOWNLOADSTATUS
                        ,null);
                    }
                });
            }
        } else { //已缓存里面的item
            holder.setVisible(R.id.item_downloadeddetailing_rl, true);
            holder.setVisible(R.id.item_downloadeddetailqbks_rl, false);
            DownloadedDetailBean downloadedDetailBean = mDownloadedList.get(position);
            parseDownloaded(holder, downloadedDetailBean);

        }

    }

    /**
     * 处理正在下载的item
     */
    private void parseDownloading(BaseViewHolder holder, DownloadedDetailBean downloadedDetailBean) {
        String url = downloadedDetailBean.getUrl();
        holder.setVisible(R.id.item_downloadeddetail_pb, true);
        holder.setVisible(R.id.item_downloadeddetail_tvpb,true);
        holder.setVisible(R.id.item_downloadeddetail_status2,true);
        holder.setVisible(R.id.item_downloadeddetail_status1,false);
        holder.setText(R.id.item_downloadeddetail_chapterName, downloadedDetailBean.getChapterName());
        holder.setText(R.id.item_downloadeddetail_cwName, downloadedDetailBean.getCwName());
        if (!TextUtils.isEmpty(url) && url.endsWith("mp4")) {
            //获取文件下载信息
            String fileName = mDownloadManager.getFileName(url);
            if (fileName == null) {
                holder.setProgress(R.id.item_downloadeddetail_pb, 0);
                holder.setText(R.id.item_downloadeddetail_tvpb,"0.00M/0.00M");
                holder.setText(R.id.item_downloadeddetail_status2,"已暂停");
            }else{
                DownloadManager.DownloadStatus status = mDownloadManager.getStatus(url);
                int progress = mDownloadManager.getProgress(url);
                long fileSize1 = mDownloadManager.getFileSize(url); //文件总大小
                long fileDownloadedSize = mDownloadManager.getFileDownloadedSize(url); //文件以及下载的大小
                String downloadSize = FileUtil.FormetFileSize(fileDownloadedSize);
                String fileSize = FileUtil.FormetFileSize(fileSize1);

                startProgress(url,holder);

                holder.setProgress(R.id.item_downloadeddetail_pb, progress);

                if (fileSize1 == 0) {
                    holder.setText(R.id.item_downloadeddetail_tvpb,"0.00M/0.00M");
                } else {
                    holder.setText(R.id.item_downloadeddetail_tvpb,downloadSize + "/" + fileSize);
                }
                String text2 = "";
                switch (status) {
                    case DOWNLOADING:
                        text2 = "下载中";
                        break;
                    case STOP:
                        text2 = "已暂停";
                        break;
                    case WAITTING:
                        text2 = "等待中";
                        break;
                    case FAIL:
                        text2 = "已暂停";
                        break;
                    case SUCCESS:
                        text2 = "已缓存";
                        break;
                }
                holder.setText(R.id.item_downloadeddetail_status2,text2);
            }
        }else{
            holder.setText(R.id.item_downloadeddetail_status2,"该视频暂不支持下载");
            holder.setText(R.id.item_downloadeddetail_tvpb,"");
            holder.setProgress(R.id.item_downloadeddetail_pb, 0);
        }

    }

    /**
     * 处理已经下载完成的item
     */
    private void parseDownloaded(BaseViewHolder holder, DownloadedDetailBean downloadedDetailBean) {
        holder.setVisible(R.id.item_downloadeddetail_pb, false);
        holder.setVisible(R.id.item_downloadeddetail_tvpb,false);
        holder.setVisible(R.id.item_downloadeddetail_status2,false);
        holder.setVisible(R.id.item_downloadeddetail_status1,true);
        holder.setText(R.id.item_downloadeddetail_chapterName, downloadedDetailBean.getChapterName());
        holder.setText(R.id.item_downloadeddetail_cwName, downloadedDetailBean.getCwName());
        String url = downloadedDetailBean.getUrl();
        if (!TextUtils.isEmpty(url)) {
            long fileSize1 = mDownloadManager.getFileSize(url); //文件总大小

            //刚开始使用 LoadDataManager做下载
//            if (fileSize1 == 0) { //兼容低版本
//                LoadDataManager.getInstance(mContext).setUserflag(UserInfor.getInstance().getUserid());
//                EntityBean bean = LoadDataManager.getInstance(mContext).getDownInfoForDownPath(url);
//                if (bean != null) {
//                    String totalFile = bean.getString("totalLength");
//                    if (totalFile != null) {
//                        fileSize1 = Long.parseLong(totalFile);
//                    }
//                }
//            }

            String fileSize = FileUtil.FormetFileSize(fileSize1);
            holder.setText(R.id.item_downloadeddetail_status1, fileSize);
        }
    }

    private void startProgress(String url, final BaseViewHolder holder){
        mDownloadManager.setOnFileDownloadStatusListener(url, new OnFileDownloadStatusListener() {
            @Override
            public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(1,holder,downloadFileInfo);
            }

            @Override
            public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(2,holder,downloadFileInfo);
            }

            @Override
            public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(3,holder,downloadFileInfo);
            }

            @Override
            public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(4,holder,downloadFileInfo);
            }

            @Override
            public void onFileDownloadStatusFailed(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(5,holder,downloadFileInfo);
            }
        });
    }

    private void updateProgressPartly(int mark, BaseViewHolder holder,DownloadFileInfo downloadFileInfo) {
        long downloadSize = downloadFileInfo.getDownloadSize();
        long fileSize = downloadFileInfo.getFileSize();
        int progress = downloadFileInfo.getProgress();
        String url = downloadFileInfo.getUrl();
        String fileDownloadedSize = FileUtil.FormetFileSize(downloadSize);
        String fileSize2 = FileUtil.FormetFileSize(fileSize);
        holder.setProgress(R.id.item_downloadeddetail_pb, progress);
        if (fileSize == 0) {
            holder.setText(R.id.item_downloadeddetail_tvpb,"0.00M/0.00M");
        } else {
            holder.setText(R.id.item_downloadeddetail_tvpb,fileDownloadedSize + "/" + fileSize2);
        }
        String text2 = "";
        switch (mark) {
            case 1:
                text2 = "等待中";
               // checkStatus(2);
                break;
            case 2:
                text2 = "下载中" ;
               // checkStatus(2);
                break;
            case 3:
                text2 = "已暂停" ;
               // show(STOP);
                break;
            case 4: //下载成功
               // toRefresh(url);
                break;
            case 5: //下载失败
                text2 = "已暂停";
               // show(STOP);
                break;
        }
        holder.setText(R.id.item_downloadeddetail_status2,text2);
    }

}
